package org.geekbang.thinking.in.spring.ioc.overview.dependency.container;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Map;

/**
 * 注解 {@link org.springframework.context.ApplicationContext} 作为 IoC 容器示例
 *
 * @author <a href="mailto:hushengjin1993@gmail.com">HuShengjin</a>
 * @date Created on 2020/7/10 10:26
 * @since
 */
public class AnnotationApplicationContextAsIoCContainerDemo {

    public static void main(String[] args) {
        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(AnnotationApplicationContextAsIoCContainerDemo.class);
        // 启动应用上下文
        applicationContext.refresh();
        lookupCollectionByType(applicationContext);

        // 关闭
        applicationContext.close();
    }

    /**
     * 通用 Java 代码的方式, 定义了一个 Bean
     *
     * @return org.geekbang.thinking.in.spring.ioc.overview.domain.User
     */
    @Bean
    public User user() {
        User user = new User();
        user.setId(1L);
        user.setName("小马哥");
        return user;
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory factory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = factory.getBeansOfType(User.class);
            System.out.println("查找到的所有的 User 集合对象：" + users);
        }
    }

}
